package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 监听延迟队列并取消订单
 */
@Component
@Slf4j
public class OrderTimeoutListener {

    @Autowired
    private OrderMapper orderMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "order.delayed.queue", durable = "true"),
            exchange = @Exchange(name = "order.delayed.exchange", delayed = "true"),
            key = "order.delayed"
    ))
    public void handleExpiredOrder(Long orderId) {
        log.info("订单超时，检查支付状态：{}",orderId);
        // 1.查询订单
        Orders orders = orderMapper.getById(orderId);
        // 2.获取支付状态
        Integer payStatus = orders.getPayStatus();
        // 3.判断是否为0（未支付）
        if (!Objects.equals(payStatus, Orders.UN_PAID)){
            // 4.若不是0，则直接返回
            return;
        }
        // 5 若是0，说明支付超时，需要取消订单,并恢复库存
        Orders orders1 = Orders.builder()
                .id(orders.getId())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .cancelReason("支付超时")
                .build();
        orderMapper.update(orders1);
    }
}

//@Component
//@Slf4j
//public class OrderTimeoutListener {
//
//    @Autowired
//    private OrderMapper orderMapper;
//
//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(name = "order.delayed.queue", durable = "true"),
//            exchange = @Exchange(name = "order.delayed.exchange", type = "x-delayed-message",
//                    arguments = @Argument(name = "x-delayed-type", value = "direct")),
//            key = "order.delayed"
//    ))
//    public void handleExpiredOrder(Long orderId) {
//        log.info("订单 {} 超时检查", orderId);
//
//        // 1. 查询订单
//        Orders orders = orderMapper.getById(orderId);
//        if (orders == null) {
//            log.warn("订单 {} 不存在，可能已被手动取消", orderId);
//            return;
//        }
//
//        // 2. 获取支付状态
//        Integer payStatus = orders.getPayStatus();
//        log.info("订单 {} 当前支付状态：{}", orderId, payStatus);
//
//        // 3. 若已支付，则无需取消
//        if (!Objects.equals(payStatus, Orders.UN_PAID)) {
//            log.info("订单 {} 已支付，跳过取消流程", orderId);
//            return;
//        }
//
//        // 4. 未支付，执行取消订单
//        log.info("订单 {} 未支付，执行超时取消", orderId);
//        orders.setStatus(Orders.CANCELLED);
//        orders.setCancelTime(LocalDateTime.now());
//        orders.setCancelReason("支付超时");
//        orderMapper.update(orders);
//
//        log.info("订单 {} 超时已取消", orderId);
//    }
//}

